##########
# Crossing Borders: Main Analyses
#########

rm(list = ls())
library(lfe)
library(texreg)
library(here)
library(data.table)
library(qs)
library(tidyverse)


cb <- qread(here("data", "cb.qs")); setDT(cb)

source(here("code", "functions.R"))

# Use 1991 population for 1987 --------------------------------------------
cb1991 <- cb %>% filter(year == 1991) %>% dplyr::select(bfs19, popJanTotal) %>% mutate(year = 1987) %>% rename(popJanTotal2 = popJanTotal)

cb <- cb %>% left_join(cb1991)

cb$popJanTotal[which(cb$year == 1987)] <- cb$popJanTotal2[which(cb$year == 1987)]

cb$popJanTotal2 <- NULL

#Run event study models with this data
#Control: 15--30
mod_pol_es <- felm_cb(
  outcome = "frPrct",
  f = as.formula(paste0("frPrct ~ border15_1987 + border15_1991 + border15_1995 + border15_2003 + border15_2007 + border15_2011 + border15_2015 + border15_2019 | bfs19 + year | 0 | bfs19"))
)

mod_pol_es_weights <- felm_cb(
  outcome = "frPrct",
  f = as.formula(paste0("frPrct ~ border15_1987 + border15_1991 + border15_1995 + border15_2003 + border15_2007 + border15_2011 + border15_2015 + border15_2019 | bfs19 + year | 0 | bfs19")),
  weights = "popJanTotal"
)

#Control: 30--45
mod_pol_es_45 <- felm_cb(
  outcome = "frPrct", control = "45",
  f = as.formula(paste0("frPrct ~ border15_1987 + border15_1991 + border15_1995 + border15_2003 + border15_2007 + border15_2011 + border15_2015 + border15_2019 | bfs19 + year | 0 | bfs19"))
)

mod_pol_es_weights_45 <- felm_cb(
  outcome = "frPrct", control = "45",
  f = as.formula(paste0("frPrct ~ border15_1987 + border15_1991 + border15_1995 + border15_2003 + border15_2007 + border15_2011 + border15_2015 + border15_2019 | bfs19 + year | 0 | bfs19")),
  weights = "popJanTotal"
)


#Control: 30--60
mod_pol_es_60 <- felm_cb(
  outcome = "frPrct", control = "60",
  f = as.formula(paste0("frPrct ~ border15_1987 + border15_1991 + border15_1995 + border15_2003 + border15_2007 + border15_2011 + border15_2015 + border15_2019 | bfs19 + year | 0 | bfs19"))
)

mod_pol_es_weights_60 <- felm_cb(
  outcome = "frPrct", control = "60",
  f = as.formula(paste0("frPrct ~ border15_1987 + border15_1991 + border15_1995 + border15_2003 + border15_2007 + border15_2011 + border15_2015 + border15_2019 | bfs19 + year | 0 | bfs19")),
  weights = "popJanTotal"
)

Texreg(
  list(
    mod_pol_es,
    mod_pol_es_weights,
    
    mod_pol_es_45,
    mod_pol_es_weights_45,
    
    mod_pol_es_60,
    mod_pol_es_weights_60
  ),
  custom.header = list("Percent Support for Anti-Immigrant Parties" = 1:6),
  custom.coef.map = list(
    "border15_1987" = "0--15 Minutes X 1987",
    "border15_1991" = "0--15 Minutes X 1991",
    "border15_1995" = "0--15 Minutes X 1995",
    "border15_2003" = "0--15 Minutes X 2003",
    "border15_2007" = "0--15 Minutes X 2007",
    "border15_2011" = "0--15 Minutes X 2011",
    "border15_2015" = "0--15 Minutes X 2015",
    "border15_2019" = "0--15 Minutes X 2019"
  ),
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), 3),
                         "Control Group" = c(rep("15--30 Min", 2), rep("30--45 Min", 2), rep("30--60 Min", 2))),
  caption = "Event Study of Political Effects on Support for Anti-Immigrant Parties in Federal Parliamentary Elections. 
  Outcome: Support for Anti-Immigrant Parties in Federal Parliamentary Elections. 
  Sample: Border Region, 1987--2019. The baseline year is 1999. 
  In models that include population weights, the 1991 weights are used for 1987.",
  label = "tab:esPol",
  file = here("tables", "esPol.tex"),
  sideways = F
)


cb <- cb %>% filter(year != 1987)

# 1. Political outcomes ---------------------------------------------

# 1.a. Main Political outcome ---------------------------------------------
mod_pol <- felm_cb(outcome = "frPrct")
mod_pol_weights <- felm_cb("frPrct", weights = "popJanTotal")


#Alternative control group at 30-45
mod_pol_45 <- felm_cb(outcome = "frPrct", control = "45")
mod_pol_weights_45 <- felm_cb("frPrct", weights = "popJanTotal", control = "45")


#Alternative control group at 30-60
mod_pol_60 <- felm_cb(outcome = "frPrct", control = "60")
mod_pol_weights_60 <- felm_cb("frPrct", weights = "popJanTotal", control = "60")


Texreg(
  list(mod_pol, mod_pol_weights, mod_pol_45, mod_pol_weights_45, mod_pol_60, mod_pol_weights_60),
  custom.header = list("Percent Support for Anti-Immigrant Parties" = 1:4),
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), 3),
                         "Control Group" = c(rep("15--30 Min", 2), rep("30--45 Min", 2), rep("30--60 Min", 2))),
  caption = "Baseline Political Effects on Support for Anti-Immigrant Parties in Federal Parliamentary Elections. 
  Outcome: Percentage Support for Anti-Immigrant Parties. Sample: Border Region, 1991--2019 Elections. 
  Weights are based on the population size of each municipality.",
  label = "tab:baselinePolitical",
  file = here("tables", "baselinePolitical.tex"),
  sideways = F
)

## 1.b. Political outcome other parties ------------------------------------
mod_cd <- felm_cb("cdPrct") #CVP EVP: Christian Democratic People's Party; Evangelical People's Party
mod_gr <- felm_cb("grPrct") #GPS GLP: Green Party; Green Liberal Party
mod_sp <- felm_cb("spPrct") #SP
mod_fdp <- felm_cb("fdpPrct") #FDP
mod_other_parties <- felm_cb("otherPrct") 

mod_cd_wt <- felm_cb("cdPrct", weights = "popJanTotal")
mod_gr_wt <- felm_cb("grPrct", weights = "popJanTotal")
mod_sp_wt <- felm_cb("spPrct", weights = "popJanTotal")
mod_fdp_wt <- felm_cb("fdpPrct", weights = "popJanTotal")
mod_other_parties_wt <- felm_cb("otherPrct", weights = "popJanTotal")

Texreg(
  list(mod_cd, mod_cd_wt, mod_gr, mod_gr_wt, mod_sp, mod_sp_wt, mod_fdp, mod_fdp_wt, mod_other_parties, mod_other_parties_wt), 
  custom.header = list("CVP/EVP" = 1:2, "GPS/GLP" = 3:4, "SP" = 5:6, "FDP" = 7:8, "Other" = 9:10),
  custom.gof.rows = list("Weights" = c("No", "Yes", "No", "Yes", "No", "Yes", "No", "Yes", "No", "Yes")),
  caption = "Baseline Political Effects on Support for Other Parties in Federal Parliamentary Elections. 
  Outcome: Percentage Support for Other Parties. 
  Sample: Border Region, Travel Minutes $<=$ 30, 1991--2019 Elections. 
  Weights are based on the population size of each municipality.",
  label = "tab:baselinePolParties",
  file = here("tables", "baselinePoliticalParties.tex"),
  sideways = F
)


## 1.c. Political outcome other parties grouped ------------------------------------
mod_center <- felm_cb("centerPrct") 
mod_left <- felm_cb("leftPrct")

mod_center_wt <- felm_cb("centerPrct", weights = "popJanTotal")
mod_left_wt <- felm_cb("leftPrct", weights = "popJanTotal")

Texreg(
  list(mod_center, mod_center_wt, mod_left, mod_left_wt), 
  custom.header = list("Center (EVP/CVP/GLP)" = 1:2, "Left (GPS/SP)" = 3:4),
  custom.gof.rows = list("Weights" = c("No", "Yes", "No", "Yes")
  ),
  caption = "Baseline Political Effects on Support for Centrist and Leftist Parties in Federal Parliamentary Elections. 
  Outcome: Percentage Support for Centrist and Leftist Parties. 
  Sample: Border Region, Travel Minutes $<=$ 30, 1991--2019 Elections. 
  Weights are based on the population size of each municipality.",
  label = "tab:baselineCenterLeft",
  file = here("tables", "baselineCenterLeft.tex")
)

# 1.d Event-study Political model ------------------------------------------

#Override results with 1987 elections for the figure. The problem with 1987 data is that population data isn't included (we use 1991 population instead)
mod_pol_es_weights <- felm_cb(
  outcome = "frPrct",
  f = as.formula(paste0("frPrct ~ border15_1991 + border15_1995 + border15_2003 + border15_2007 + border15_2011 + border15_2015 + border15_2019 | bfs19 + year | 0 | bfs19")),
  weights = "popJanTotal"
)


# 2. First stage outcomes ---------------------------------------------

## 2. a. Main first stage outcome ---------------------------------------------
mod_fs98 <- felm_cb("dfA98")
mod_fs98_weights <- felm_cb("dfA98", weights = "popJanTotal")


mod_fsC <- felm_cb("dfAC")
mod_fsC_weights <- felm_cb("dfAC", weights = "popJanTotal")

mod_fs98_45 <- felm_cb("dfA98", control = "45")
mod_fs98_weights_45 <- felm_cb("dfA98", weights = "popJanTotal", control = "45")

mod_fsC_45 <- felm_cb("dfAC", control = "45")
mod_fsC_weights_45 <- felm_cb("dfAC", weights = "popJanTotal", control = "45")

Texreg(
  list(
    mod_fs98, 
    mod_fs98_weights,
    mod_fs98_45,
    mod_fs98_weights_45,
    
    mod_fsC,
    mod_fsC_weights,
    mod_fsC_45,
    mod_fsC_weights_45
    
  ),
  custom.header = list("Relative to 1998 Swiss" = 1:4, "Relative to Current Swiss" = 5:8),
  custom.gof.rows = list(
    "Weights" = c("No", "Yes", "No", "Yes", "No", "Yes", "No", "Yes"),
    "Control Group" = c("15--30 Min", "15--30 Min", "30--45 Min", "30--45 Min", "15--30 Min", "15--30 Min", "30--45 Min", "30--45 Min")),
  caption = "Baseline Immigration Effects. Outcome: Total Immigration (Resident Immigrants and Cross-Border Workers) Relative to 1998 and Current Swiss Population. 
  Sample: Border Region, 1996--2016. Weights are based on the population size of each municipality.",
  label = "tab:baselineImm",
  file = here("tables", "baselineImm.tex"),
  sideways = F
)


## 2.b Immigration outcomes split between residents and CBW -----------------
mod_res98 <- felm_cb("immA98")
mod_res98_weights <- felm_cb("immA98", weights = "popJanTotal")
mod_cbw98 <- felm_cb("cbw98")
mod_cbw98_weights <- felm_cb("cbw98", weights = "popJanTotal")

mod_resC <- felm_cb("immAC")
mod_resC_weights <- felm_cb("immAC", weights = "popJanTotal")
mod_cbwC <- felm_cb("cbwC")
mod_cbwC_weights <- felm_cb("cbwC", weights = "popJanTotal")

Texreg(
  list(
    mod_cbw98,
    mod_cbw98_weights,
    mod_cbwC,
    mod_cbwC_weights,
    
    mod_res98,
    mod_res98_weights,
    mod_resC,
    mod_resC_weights
  ),
  custom.header = list("Cross-Border Workers" = 1:4, "Resident Immigrants" = 5:8),
  custom.model.names = c(rep("Resident", 2), rep("CBWs", 2), rep("Resident", 2), rep("CBWs", 2)),
  custom.gof.row = list(
    "Weights" = rep(c("No", "Yes"), times = 4)
  ),
  caption = "Effects on Immigration by Resident Immigrants and Cross-Border Workers (CBWs). 
  Outcome: Resident Immigrants (Models 1, 2, 5, 6) or CBWs (Models 3, 4, 7, 8) Relative to 1998 Swiss (Models 1--4) or Current Swiss (Models 5--8) Population. 
  Sample: Border Region, Travel Minutes $<=$ 30, 1991--2018 (Resident Immigrants) or 1996--2016 (CBWs). Weights are based on the population size of each municipality.",
  label = "tab:splitImm",
  sideways = F,
  file = here("tables", "splitImm.tex")
)



# 2.C Event-study Immigration model ----------------------------------------

#Relative to 1998 Swiss
##Write formula
df_es_form <- as.formula(
  paste0(
    "dfA98 ~ ",
    paste0("border15_", c(1996:1998, 2000:2016), collapse = " + "),
    " | bfs19 + year | 0 | bfs19")
)

#Run regressions (without and with weights)
mod_df_es_98 <- felm_cb(outcome = "dfA98", f = df_es_form, data = cb %>% filter(year %in% 1996:2016))
mod_df_es_weights_98 <- felm_cb(outcome = "dfA98", f = df_es_form, data = cb %>% filter(year %in% 1996:2016), weights = "popJanTotal")
mod_df_es_weights_98 %>% broom::tidy(conf.int = T)

10.5/((cb %>% filter(BR == 1, travelMUNmin < 15, year  == 1999) %>% summarise(out = weighted.mean(dfA98, w = popJanTotal, na.rm = T))) %>% pull(out))

mod_df_es_weights_98 %>% broom::tidy(conf.int = T) %>% pull(conf.low)/((cb %>% filter(BR == 1, travelMUNmin < 15, year == 1999) %>% summarise(out = weighted.mean(dfA98, w = popJanTotal, na.rm = T))) %>% pull(out))
mod_df_es_weights_98 %>% broom::tidy(conf.int = T) %>% pull(conf.high)/((cb %>% filter(BR == 1, travelMUNmin < 15, year == 1999) %>% summarise(out = weighted.mean(dfA98, w = popJanTotal, na.rm = T))) %>% pull(out))



#Relative to Current Swiss
df_es_form_C <- as.formula(
  paste0(
    "dfAC ~ ",
    paste0("border15_", c(1996:1998, 2000:2016), collapse = " + "),
    " | bfs19 + year | 0 | bfs19")
)

#Run regressions (without and with weights)
mod_df_es_C <- felm_cb(outcome = "dfAC", f = df_es_form_C, cb %>% filter(year %in% 1996:2016))
mod_df_es_weights_C <- felm_cb(outcome = "dfAC", f = df_es_form_C, cb %>% filter(year %in% 1996:2016), weights = "popJanTotal")

Texreg(
  list(
    mod_df_es_98,
    mod_df_es_weights_98,
    
    mod_df_es_C,
    mod_df_es_weights_C
  ),
  custom.coef.map = list(
    "border15_1996" = "0--15 Minutes X 1996",
    "border15_1997" = "0--15 Minutes X 1997",
    "border15_1998" = "0--15 Minutes X 1998",
    "border15_2000" = "0--15 Minutes X 2000",
    "border15_2001" = "0--15 Minutes X 2001",
    "border15_2002" = "0--15 Minutes X 2002",
    "border15_2003" = "0--15 Minutes X 2003",
    "border15_2004" = "0--15 Minutes X 2004",
    "border15_2005" = "0--15 Minutes X 2005",
    "border15_2006" = "0--15 Minutes X 2006",
    "border15_2007" = "0--15 Minutes X 2007",
    "border15_2008" = "0--15 Minutes X 2008",
    "border15_2009" = "0--15 Minutes X 2009",
    "border15_2010" = "0--15 Minutes X 2010",
    "border15_2011" = "0--15 Minutes X 2011",
    "border15_2012" = "0--15 Minutes X 2012",
    "border15_2013" = "0--15 Minutes X 2013",
    "border15_2014" = "0--15 Minutes X 2014",
    "border15_2015" = "0--15 Minutes X 2015",
    "border15_2016" = "0--15 Minutes X 2016"
  ),
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), 2)),
  custom.header = list("Relative to 1998 Swiss" = 1:2, "Relative to Current Swiss" = 3:4),
  caption = "Event Study on Immigrant Workers. 
  Outcome: Share of Immigrant Workers Relative to 1998 and Current Swiss Population. 
  Sample: Border Region, Travel Minutes $<=$ 30, 1991--2019. 
  The baseline year is 1999. 
  Weights are based on the population size of each municipality.",
  label = "tab:esdfA",
  file = here("tables", "esdfA.tex"),
  single.row = T
)




# 3. Robustness: --------------------------------------

## 3.A. 5-30 minute increments --------------------------------------------------
cb <- cb %>% 
  mutate(border10 = as.integer(travelMUNmin < 10),
         border20 = as.integer(travelMUNmin < 20),
         border25 = as.integer(travelMUNmin < 25),
         border35 = as.integer(travelMUNmin < 35), #Not actually needed--remove
         transBorder10 = border10 * transition,
         transBorder20 = border20 * transition,
         transBorder25 = border25 * transition,
         transBorder35 = border35 * transition, #Not actually needed--remove
         freeBorder10 = border10 * free,
         freeBorder20 = border20 * free,
         freeBorder25 = border25 * free,
         freeBorder35 = border35 * free, #Not actually needed--remove
         transTraveMUNmin = travelMUNmin * transition,
         freeTraveMUNmin = travelMUNmin * free
         )

mod_pol5 <- felm_cb(outcome = "frPrct", 
        f = as.formula(paste0("frPrct ~ transBorder5 + freeBorder5 | bfs19 + year | 0 | bfs19")),
        weights = "popJanTotal")

mod_pol10 <- felm_cb(outcome = "frPrct", 
        f = as.formula(paste0("frPrct ~ transBorder10 + freeBorder10 | bfs19 + year | 0 | bfs19")),
        weights = "popJanTotal")

mod_pol20 <- felm_cb(outcome = "frPrct", 
        f = as.formula(paste0("frPrct ~ transBorder20 + freeBorder20 | bfs19 + year | 0 | bfs19")),
        weights = "popJanTotal")

mod_pol25 <- felm_cb(outcome = "frPrct", 
        f = as.formula(paste0("frPrct ~ transBorder25 + freeBorder25 | bfs19 + year | 0 | bfs19")),
        weights = "popJanTotal")

mod_pol_cont <- felm_cb(outcome = "frPrct", 
        f = as.formula(paste0("frPrct ~ log(transTraveMUNmin + 1) + log(freeTraveMUNmin + 1) | bfs19 + year | 0 | bfs19")),
        weights = "popJanTotal")

Texreg(
  list(mod_pol5, mod_pol10, mod_pol20, mod_pol25, mod_pol_cont),
  custom.header = list("Percent Support for Anti-Immigrant Parties" = 1:5 ),
  custom.gof.rows = list("Weights" = c("Yes", "Yes", "Yes", "Yes", "Yes")),
  custom.coef.map = list("transBorder5" = "0--5 Minutes X Transition",
                         "freeBorder5" = "0--5 Minutes X Free",
                         "transBorder10" = "0--10 Minutes X Transition",
                         "freeBorder10" = "0--10 Minutes X Free",
                         "transBorder20" = "0--20 Minutes X Transition",
                         "freeBorder20" = "0--20 Minutes X Free",
                         "transBorder25" = "0--25 Minutes X Transition",
                         "freeBorder25" = "0--25 Minutes X Free",
                         "log(transTraveMUNmin + 1)" = "Log (time to border crossing + 1) X Transition",
                         "log(freeTraveMUNmin + 1)" = "Log (time to border crossing + 1) X Free"
  ),
  caption = "Baseline Political Effects with Varying Times to Border Crossings as Treatment Thresholds. 
  Outcome: Percentage Support for Anti-Immigrant Parties in Federal Parliamentary Elections. 
  Sample: Border Region, Travel Minutes $<=$ 30, 1991--2019 Elections. 
  Weights are based on the population size of each municipality.",
  label = "tab:baselinePoliticalDistances",
  file = here("tables", "baselinePoliticalDistances.tex"),
  fontsize = "footnotesize"
)







## 3.C. Daytime foreigner by region ---------------------------------------------

# Models for origin-specific measures of daytime foreigners
dforiginMods <- expand.grid(
  outcome = paste0("df", c("DE", "FR", "IT", "OE"), rep(c("98", "C"), each = 4)),
  weights = c("", "popJanTotal")
)

setDT(dforiginMods)

dforiginMods[ , reg := .(.(felm_cb(outcome = outcome, chatty = F, weights = weights))), by = .(outcome, weights)]

dforiginMods[ , print(summary(reg[[1]])), by = .(outcome, weights)]

Texreg(
  dforiginMods[grepl("98", outcome)][order(outcome, weights) , reg],
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), times = dforiginMods[grepl("98", outcome) , uniqueN(outcome)])),
  caption = "Effects on Immigrant Workers by Origin. 
  Outcome: Immigrant Workers (Split by Origin) Relative to 1998 Swiss Population. 
  Sample: Border Region, Travel Minutes $<=$ 30, 1996--2016. 
  Weights are based on the population size of each municipality.",
  custom.header = list(
    "Germany" = 1:2,
    "France" = 3:4,
    "Italy" = 5:6,
    "Austria" = 7:8
  ),
  label = "tab:byOrigin_98",
  file = here("tables", "byOrigin_98.tex"),
  fontsize = "footnotesize", sideways = F)

Texreg(
  dforiginMods[!grepl("98", outcome)][order(outcome, weights) , reg],
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), times = dforiginMods[!grepl("98", outcome) , uniqueN(outcome)])),
  caption = "Effects on Immigrant Workers by Origin. 
  Outcome: Immigrant Workers (Split by Origin) Relative to Current Swiss Population. 
  Sample: Border Region, Travel Minutes $<=$ 30, 1996--2016. 
  Weights are based on the population size of each municipality.",
  custom.header = list(
    "Germany" = 1:2,
    "France" = 3:4,
    "Italy" = 5:6,
    "Austria" = 7:8
  ),
  label = "tab:byOrigin_C",
  file = here("tables", "byOrigin_C.tex"),
  fontsize = "footnotesize", sideways = F)

## 3.C. Models split by language region ---------------------------------------------

### 3.C.1. German speaking---------------------------------------------
dforiginModsDE <- expand.grid(
  outcome = paste0("df", c("A" ,"DE", "FR", "IT", "OE"), rep(c("98", "C"), each = 5)),
  weights = c("", "popJanTotal")
)

setDT(dforiginModsDE)

dforiginModsDE[ , reg := .(.(felm_cb(outcome = outcome, chatty = F, weights = weights, data = cb[languagereg2019 == 1]))), by = .(outcome, weights)]


Texreg(
  dforiginModsDE[grepl("98", outcome)][order(outcome, weights) , reg],
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), times = dforiginModsDE[grepl("98", outcome) , uniqueN(outcome)])),
  caption = "Effects on Immigrant Workers by Origin. Outcome: Immigrant Workers (Split by Origin) Relative to 1998 Swiss Population. Sample: German-Speaking Municipalities, Border Region, Travel Minutes $<=$ 30, 1996--2016. Weights are based on the population size of each municipality.",
  custom.header = list(
    "All origins" = 1:2,
    "Germany" = 3:4,
    "France" = 5:6,
    "Italy" = 7:8,
    "Austria" = 9:10
  ),
  label = "tab:byOrigin_98_DE",
  file = here("tables", "byOrigin_98_DE.tex"),
  fontsize = "footnotesize",
  sideways = F
  )

Texreg(
  dforiginModsDE[!grepl("98", outcome)][order(outcome, weights) , reg],
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), times = dforiginModsDE[!grepl("98", outcome) , uniqueN(outcome)])),
  caption = "Effects on Immigrant Workers by Origin. Outcome: Immigrant Workers (Split by Origin) Relative to Current Swiss Population. Sample: German-Speaking Municipalities, Border Region, Travel Minutes $<=$ 30, 1996--2016. Weights are based on the population size of each municipality.",
  custom.header = list(
    "All origins" = 1:2,
    "Germany" = 3:4,
    "France" = 5:6,
    "Italy" = 7:8,
    "Austria" = 9:10
  ),
  label = "tab:byOrigin_C_DE",
  file = here("tables", "byOrigin_C_DE.tex"),
  fontsize = "footnotesize",
  sideways = F)

### 3.C.2. French speaking---------------------------------------------
dforiginModsFR <- expand.grid(
  outcome = paste0("df", c("A","DE", "FR", "IT", "OE"), rep(c("98", "C"), each = 5)),
  weights = c("", "popJanTotal")
)

setDT(dforiginModsFR)

dforiginModsFR[ , reg := .(.(felm_cb(outcome = outcome, chatty = F, weights = weights, data = cb[languagereg2019 == 2]))), by = .(outcome, weights)]

Texreg(
  dforiginModsFR[grepl("98", outcome)][order(outcome, weights) , reg],
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), times = dforiginModsFR[grepl("98", outcome) , uniqueN(outcome)])),
  caption = "Effects on Immigrant Workers by Origin. Outcome: Immigrant Workers (Split by Origin) Relative to 1998 Swiss Population. Sample: French-Speaking Municipalities, Border Region, Travel Minutes $<=$ 30, 1996--2016. Weights are based on the population size of each municipality.",
  custom.header = list(
    "All origins" = 1:2,
    "Germany" = 3:4,
    "France" = 5:6,
    "Italy" = 7:8,
    "Austria" = 9:10
  ),
  label = "tab:byOrigin_98_FR",
  file = here("tables", "byOrigin_98_FR.tex"),
  fontsize = "footnotesize",
  sideways = F)

Texreg(
  dforiginModsFR[!grepl("98", outcome)][order(outcome, weights) , reg],
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), times = dforiginModsFR[!grepl("98", outcome) , uniqueN(outcome)])),
  caption = "Effects on Immigrant Workers by Origin. Outcome: Immigrant Workers (Split by Origin) Relative to Current Swiss Population. Sample: French-Speaking Municipalities, Border Region, Travel Minutes $<=$ 30, 1996--2016. Weights are based on the population size of each municipality.",
  custom.header = list(
    "All origins" = 1:2,
    "Germany" = 3:4,
    "France" = 5:6,
    "Italy" = 7:8,
    "Austria" = 9:10
  ),
  label = "tab:byOrigin_C_FR",
  file = here("tables", "byOrigin_C_FR.tex"),
  fontsize = "footnotesize",
  sideways = F)

### 3.C.3. Italian speaking---------------------------------------------
dforiginModsIT <- expand.grid(
  outcome = paste0("df", c("A","DE", "FR", "IT", "OE"), rep(c("98", "C"), each = 5)),
  weights = c("", "popJanTotal")
)

setDT(dforiginModsIT)

dforiginModsIT[ , reg := .(.(felm_cb(outcome = outcome, chatty = F, weights = weights, data = cb[languagereg2019 > 2]))), by = .(outcome, weights)]

Texreg(
  dforiginModsIT[grepl("98", outcome)][order(outcome, weights) , reg],
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), times = dforiginModsIT[grepl("98", outcome) , uniqueN(outcome)])),
  caption = "Effects on Immigrant Workers by Origin. Outcome: Immigrant Workers (Split by Origin) Relative to 1998 Swiss Population. Sample: Italian-Speaking Municipalities, Border Region, Travel Minutes $<=$ 30, 1996--2016. Weights are based on the population size of each municipality.",
  custom.header = list(
    "All origins" = 1:2,
    "Germany" = 3:4,
    "France" = 5:6,
    "Italy" = 7:8,
    "Austria" = 9:10
  ),
  label = "tab:byOrigin_98_IT",
  file = here("tables", "byOrigin_98_IT.tex"),
  fontsize = "footnotesize",
  sideways = F)

Texreg(
  dforiginModsIT[!grepl("98", outcome)][order(outcome, weights) , reg],
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), times = dforiginModsIT[!grepl("98", outcome) , uniqueN(outcome)])),
  caption = "Effects on Immigrant Workers by Origin. Outcome: Immigrant Workers (Split by Origin) Relative to Current Swiss Population. Sample: Italian-Speaking Municipalities, Border Region, Travel Minutes $<=$ 30, 1996--2016. Weights are based on the population size of each municipality.",
  custom.header = list(
    "All origins" = 1:2,
    "Germany" = 3:4,
    "France" = 5:6,
    "Italy" = 7:8,
    "Austria" = 9:10
  ),
  label = "tab:byOrigin_C_IT",
  file = here("tables", "byOrigin_C_IT.tex"),
  fontsize = "footnotesize",
  sideways = F)



# 4 Regression with covariates ----------------------------------------------
cb <- cb %>% mutate(ce_eu_log = log(ce_eu + 1),
              former_yugo_log = log(former_yugo + 1),
              turkey_log = log(turkey + 1),
              other_log = log(other + 1),
              popJanSwiss_log = log(popJanSwiss))


mod_Swiss <- felm(frPrct ~ freeBorder15 + transBorder15 + popJanSwiss_log | bfs19 + year | 0 | bfs19,
     data = cb %>% filter(travelMUNmin < 30, BR == 1))

mod_Swiss_weights <- felm(frPrct ~ freeBorder15 + transBorder15 + popJanSwiss_log | bfs19 + year | 0 | bfs19,
                          weights = cb %>% filter(travelMUNmin < 30, BR == 1, complete.cases(popJanTotal)) %>% pull(popJanTotal), 
                          data = cb %>% filter(travelMUNmin < 30, BR == 1, complete.cases(popJanTotal)))

mod_other_foreigners <- felm(frPrct ~ freeBorder15 + transBorder15 + ce_eu_log + former_yugo + turkey + other | bfs19 + year | 0 | bfs19,
                             data = cb %>% filter(travelMUNmin < 30, BR == 1))

mod_other_foreigners_weights <- felm(frPrct ~ freeBorder15 + transBorder15 + ce_eu_log + former_yugo + turkey + other | bfs19 + year | 0 | bfs19,
                                     weights = cb %>% filter(travelMUNmin < 30, BR == 1, complete.cases(popJanTotal)) %>% pull(popJanTotal), 
                                     data = cb %>% filter(travelMUNmin < 30, BR == 1, complete.cases(popJanTotal)))




Texreg(
  list(mod_Swiss, mod_Swiss_weights, mod_other_foreigners, mod_other_foreigners_weights),
  custom.header = list("Percent Support for Anti-Immigrant Parties" = 1:4),
  custom.coef.map = list(
    "transBorder15" = "0--15 Minutes X Transition",
    "freeBorder15" = "0--15 Minutes X Free",
    "popJanSwiss_log" = "Log Swiss Population",
    "ce_eu_log" = "Log Central European Population",
    "former_yugo" = "Log Former Yugoslav Population",
    "turkey" = "Log Turkish Population",
    "other" = "Log Others"),
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), 2)),
  caption = "Baseline Political Effects on Support for Anti-Immigrant Parties in Federal Parliamentary Elections. 
  Outcome: Percentage Support for Anti-Immigrant Parties. Sample: Border Region, 1991--2019 Elections. 
  Weights are based on the population size of each municipality.",
  label = "tab:baselinePoliticalControls",
  file = here("tables", "baselinePoliticalControls.tex")
)






